<template>
    <div>
        <cjj-table @getlist="getListData" ref="cjjTable" :total="total">
            <template #search>
                <el-form :model="searchContent" ref="searchFrom" :inline="true">
                    <el-form-item prop="store_name" label="提交店铺：">
                        <el-input v-model="searchContent.store_name" placeholder="店铺名称" maxlength="32">
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="brand3_id" label="所属车型：">
                        <el-select v-model="searchContent.brand3_id" placeholder="请选择">
                            <el-option
                                v-for="item in series_list"
                                :key="item.brand3_id"
                                :label="item.brand_name"
                                :value="item.brand3_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="brand_name" label="车款名：">
                        <el-input v-model="searchContent.brand_name" placeholder="车款名" maxlength="32"></el-input>
                    </el-form-item>
                    <el-form-item prop="state" label="审核状态：">
                        <el-select v-model="searchContent.state" placeholder="请选择">
                            <el-option
                                v-for="item in stateArr"
                                :key="item.id"
                                :label="item.tname"
                                :value="item.id"
                                >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button type="primary" @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </template>
            <template #default="tableSlot">
                <el-table
                    v-if="tableSlot.oHeight"
                    :data="tableData"
                    style="width: 100%"
                    :height="tableSlot.oHeight*1"
                    :header-cell-class-name="hdCellClassName" 
                    border
                    @selection-change="handleSelectionChange"
                    ref="tableList"
                    class="table-box"
                >
                    <el-table-column type="selection" :selectable='checkboxSelect' width="60" align="center"></el-table-column>
                    <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
                    <el-table-column
                        prop="sub_time"
                        label="提交时间"
                        width="160"
                        #default="{row}"
                        align="center"
                    >{{row.sub_time*1000|dateFormatter('YYYY-MM-DD HH:mm:ss')}}</el-table-column>
                    <el-table-column prop="type_name" label="车款名" min-width="250"></el-table-column>
                    <el-table-column prop="brand_name" label="所属车型" align="center" min-width="120"></el-table-column>
                    <el-table-column prop="sub_price" label="经销商提交价格(万)" align="center" min-width="140" #default="{row}">
                        <!--el-form :model="row" v-if="row.state=='1'">
                            <el-form-item prop="sub_price" :rules="[{required: true, message: '提交价格不能为空', trigger: 'blur'}]">
                                <el-input class="_center" v-model="row.sub_price" @focus="focusPrice(row, 'sub_price')" @input="row.sub_price=row.sub_price.replace(/[^0-9.]/g,'')" @blur="updatePrice(row, 'sub_price', '提交')">
                                </el-input>
                            </el-form-item>
                        </el-form-->
                        {{row.sub_price}}
                    </el-table-column>
                    <el-table-column prop="guide_price" min-width="120" align="center" label="厂商指导价(万)"></el-table-column>
                    <el-table-column prop="engine" min-width="100" align="center" label="优惠幅度" #default="{row}">
                        {{discount(row.guide_price, row.sub_price)}}
                    </el-table-column>
                    <el-table-column prop="store_name" label="提交店铺" min-width="150" align="center"></el-table-column>
                    <el-table-column prop="state" label="审核状态" align="center" width="120" #default="{row}">
                        <span :class="`state_${row.state}`">{{state_list[parseInt(row.state)].tname}}</span>
                    </el-table-column>
                    <el-table-column label="操作" width="110" align="center" fixed="right" #default="{row}">
                        <template v-if="row.state==='1'">
                            <el-button type="text" @click="examineBrand([row], 1)">通过</el-button>
                            <!--el-button type="text" @click="examineBrand(row,2)">拒绝</el-button-->
                        </template>
                        <span v-else>--</span>
                    </el-table-column>
                </el-table>
            </template>
			<template #button>
				<el-button type="primary" @click="examineBrand(multipleSelection, 1)">批量通过</el-button>
				<el-button type="primary" @click="exportData">导出</el-button>
			</template>
        </cjj-table>
    </div>
</template>
<script>
// import { dateFormatter } from '@/common/js/util.js'
import { priceAudit } from '../api'
import cjjTable from '@/components/home/CjjTable'
export default ({
    components: { cjjTable },
    data() {
        return {
            abc: 5,
            tableData: [],
            total: 0,
            series_list: [],
            searchContent: {
                is_search: true,
				brand3_id: "",
				brand_name: "",
                store_name: "",
				state: 1,
            },
			state_list: [
                {id: "", tname: "全部"},
                {id: 1, tname: "待审核"},
                {id: 2, tname: "已通过"},
                {id: 3, tname: "已拒绝"},
                {id: 4, tname: "已下架"}
            ],
            multipleSelection: [] // 选中的row
        }
    },
    computed: {
        stateArr() {
            return this.state_list.filter(item => item.id!=3)
        },
        // 优惠幅度计算
		discount: {
            get() {
			    return function(guide_price, sub_price) {
			        [guide_price, sub_price] = [parseFloat(guide_price), parseFloat(sub_price)]
                    return ((guide_price - sub_price) / guide_price * 100).toFixed(2) + '%'
			    }
            }
		}
    },
    created() {
        this.getListData()
    },
    methods: {
		exportData(){
			let origin = this.$store.state.location.origin;
			window.location.href = origin+"/admin/yt_car/index.php?act=yt_car&op=getPriceRecord&form_submit=1"
		},
        async getListData(currentPage = 1, pageSize = localStorage.getItem('pageSize') * 1 || 10) {
            let datas = {
                curpage: currentPage,
                pagesize: pageSize 
            }
            if(this.searchContent.is_search) {
                datas = {...datas, ...this.searchContent};
            }
            // console.log(datas)
            let res = await priceAudit.getPriceRecord(datas);
            this.tableData = res.data.list;
            this.series_list = res.data.series_list;
            this.total = res.data.TotalNum * 1;
        },
        // 预留接口
		focusPrice(row, key) {
			if(!row[key + '_y']) row[key + '_y'] = row[key];
		},
        // 预留接口，原本支持提交价格修改
		updatePrice(row, key = null, text = "") {
			let [data, price] = [{id: row.id}, row[key]];
			if(price) {
				price = parseFloat(price).toFixed(2);
			    data[key] = price;
				row[key] = price;
			    // 判断是否改动价格
			    if(parseFloat(row[key + '_y']) == parseFloat(price)) return;
			} else {
				this.$alert(text + "价格不能为空")
				return;
			}
			this.$confirm(`是否将${text}价格调整为 <span class="_blue">${price}万元</span> ?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                dangerouslyUseHTMLString: true,
                center: true
            }).then(() => {
		    	this.examineBrand(row, null, () => {
					row.state = "1"
				    row[key + '_y'] = price;
				})
		    }).catch(() => {
				row[key] = row[key + '_y'];
                return;         
            });
		},
        examineBrand(row, type = null, cb = null) {
            let datas = {
                type: 1
            };
            let [ids, prices] = [[], []];
            for(let value of row) {
                console.log(value)
                ids.push(value.id);
                prices.push(value.sub_price);
            }
            datas.id = ids;
            datas.price = prices;
            console.log(datas)
            priceAudit.examineBrand(datas).then(res => {
                if (res.code === 1) {
                    //if(typeof type == "number") {
                        row.map(item => {
                            item.state = (parseInt(item.state)+1).toString()
                            this.$refs.tableList.toggleRowSelection(item, false)
                            return item;
                        })
                    // }
                    typeof cb == "function" && cb()
                    this.$message.success(res.msg)
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(err => {
                this.$message.error(err)
            });
        },
        handleSearch() {
            if(!this.searchContent.is_search) this.searchContent.is_search = true;
            this.$refs.cjjTable.currentPage = 1;
            this.getListData();
        },
        handleReset() {
            this.selectTime = null;
            this.$refs.searchFrom.resetFields();
            this.searchContent.state = "";
            if(!this.searchContent.is_search) return;
            this.searchContent.is_search = false;
            this.$refs.cjjTable.currentPage = 1;
            this.getListData();
        },
        hdCellClassName() {
            return 'hdCellStyle'
        },
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
        checkboxSelect(row, rowIndex) {
            if (parseInt(row.state) != 1) {
              return false // 禁用
            }else{
              return true // 不禁用
            }
        }
    },
    mounted() {
    }

})
</script>
<style scoped lang="scss">
    /deep/.search-list .el-form-item.el-form-item--mini{
        margin-bottom:0;
    }
	.state_1{color:#FF6600}
	.state_2{color:#56A431}
	.state_3, .el-button.state4{color:#333333}
	.state_4{color:#999999}
    /deep/.el-table-column--selection .cell {
        padding-right: 10px;
    }
</style>
<style lang="scss">
    ._blue {
        color:#0683FF;
    }
</style>